<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;

use app\common\model\Goods as GoodsModel;
use my\Pinyin;
use think\Db;
use app\api\validate\Goods as GoodsValidate;
use app\common\model\ProjectCategory;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Goods extends Auth
{
    public $noNeedLogin = '';

    /**
     * 基础数据--设置商品---商品列表
     *  page
     *  limit
     *  token
     *  goods_category_id
     */
    public function lists()
    {

        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['page'])) {
                $getData['page'] = 1;
            }
            $limit = $this->request->post('limit', 10);
            $order = 'id asc';
            //顶级商品
            if (key_exists('fcatid', $getData) && isset($getData['fcatid']) && !empty($getData['fcatid'])) {
                $where['fcatid'] = $getData['fcatid'];
            }
            //栏目商品
            if (key_exists('goods_category_id', $getData) && isset($getData['goods_category_id']) && !empty($getData['goods_category_id'])) {
                $where['goods_category_id'] = $getData['goods_category_id'];
            }
            //价格排序
            if (key_exists('price', $getData) && isset($getData['price']) && !empty($getData['price'])) {
                //价格从小到大排序
                if ($getData['price'] == 'up') {
                    $order = 'goods_price asc';
                }
                //价格从大到小排序
                if ($getData['price'] == 'down') {
                    $order = 'goods_price desc';
                }
            }
            //销量排序
            if (key_exists('sale_num', $getData) && isset($getData['price']) && !empty($getData['sale_num'])) {
                //销量从小到大排序
                if ($getData['sale_num'] == 'up') {
                    $order = 'sale_num asc';
                }
                //销量从大到小排序
                if ($getData['sale_num'] == 'down') {
                    $order = 'sale_num desc';
                }
            }
            $where['status'] = 1;
            $where['store_id'] = $this->userInfo['store_id'];
            //搜索商品
            if (key_exists('keywords', $getData) && isset($getData['keywords']) && !empty($getData['keywords'])) {
                $keywords = $getData['keywords'];
            } else {
                $keywords = '';
            }
            $goodsData = Db::name('qt_goods')->where($where)
                ->where('name', 'like', '%' . $keywords . '%')
                ->field('id,name,price')
                ->order($order)
                ->paginate($limit);
            $this->result('查询成功', $goodsData, 200);
        } else {
            $this->result('请求错误', '', 204);
        }

    }

    /**
     *
     * 基础数据--设置商品--删除商品
     * good_id
     * token
     */
    public function remove()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (empty($data['goods_id'])) {
                $this->result('请求参数有误', '', 204);
            }
            //检测商品删除限制
            $result = GoodsModel::checkDel($data['goods_id']);
            if($result['code'] == 204){
                $this->result($result['msg'],'',204);
            }
            $msg = GoodsModel::destroy($data['goods_id']);

            $msg ? $this->result('删除成功', '', 200) : $this->result('删除失败', '', 204);
        } else {
            $this->result('请求错误', '', 204);
        }

    }

    /**
     * 基础数据--设置商品--增加修改商品
     * goods_id
     * token
     * name
     * price
     * goods_category_id
     * engineer_rate
     * receiver_rate
     * description
     * is_change_price
     * is_viper_pay
     * is_sale
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = new GoodsValidate();
            if (!$validate->check($data)) $this->result($validate->getError(), '', 204);
            if (key_exists('id', $data) && !empty($data['id'])) {
                $info = GoodsModel::where(['store_id' => $this->store_id, 'name' => $data['name']])->where('id','<>',$data['id'])->find();
                if (!empty($info)) $this->result('商品名称已添加', '', 204);
                //汉字转拼音
                $pinyin = new pinyin();
                $namePy = $pinyin->getpy($data['name'],false,false);
                $data['name_py'] = $namePy;
                $msg = GoodsModel::where('id', $data['id'])->update($data);
            } else {
                $info = GoodsModel::where(['store_id' => $this->store_id, 'name' => $data['name']])->find();
                if (!empty($info)) $this->result('商品名称已添加', '', 204);
                $data['store_id'] = $this->store_id;
                //汉字转拼音
                $pinyin = new pinyin();
                $namePy = $pinyin->getpy($data['name'],false,false);
                $data['name_py'] = $namePy;
                $msg = GoodsModel::create($data);
            }

            $msg ? $this->result('操作成功', '', 200) : $this->result('修改商品信息与原信息相同', '', 200);
        } else {
            $this->result('请求错误', '', 204);
        }

    }

    /**
     *商品详情
     * token
     * goods_id
     */
    public function detail()
    {
        if ($this->request->isPost()) {
            $goodsId = $this->request->post('goods_id');

            if (empty($goodsId)){
                $this->result('请求参数有误', '', 204);
            }
            $info = GoodsModel::where(['id' => $goodsId])->find();
            $this->result('获取成功', $info, 200);
        } else {
            $this->result('请求错误', '', 204);
        }

    }

    /**
     * 基础数据--设置商品---商品类别
     * token
     *
     */
    public function category()
    {
        if ($this->request->isPost()) {
            $list = ProjectCategory::where(['store_id' => $this->userInfo['id']])->column('id,name');

            $this->result('获取成功', $list, 200);
        } else {
            $this->result('请求错误', '', 204);
        }
    }

    /**
     * 商品详情页
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
//    public function detail(){
//        if($this->request->isGet())
//        {
//            $goodsId = $this->request->get('goods_id');
//            if (empty($goodsId)) {
//                $this->result('请求参数有误','',204);
//            }
//            $token = $this->request->header('token');
//            $userInfo = Db::name('qt_users')->where('login_token', $token)->find();
//            $goodsData = GoodsModel::where(['goods_id'=>$goodsId,'status'=>1])
//                ->field('goods_id,goods_name,goods_desc,goods_tag,market_price,goods_price,goods_album,goods_content,del_address,sale_num,give_point,is_ship')
//                ->find();
//            $userDiscount = Db::name('qt_rank')->where('id',1)->find();
//            $goodsPrice = $goodsData['goods_price'] * $userDiscount['discount'] /100 ;
//            $goodsData['vip_price'] = sprintf("%.2f",$goodsPrice) ;
//            $goodsData['discount'] = $userDiscount['discount'] /10;
//            if(empty($goodsData)){
//                $this->result('商品被删除了','',204);
//            }
//            //处理商品标签
//            if(!empty($goodsData['goods_tag'])){
//                $goodsData['goods_tag'] = explode(',',$goodsData['goods_tag']);
//            }
//            //处理商品图片
//            if(!empty($goodsData['goods_album'])){
//                $imageRes = explode(',',$goodsData['goods_album']);
//                foreach ($imageRes as $key=>$value){
//                    $imageRes[$key] = get_img_path($value);
//                }
//            }
//            $goodsData['goods_album'] = $imageRes;
//            $goodsSku = Goodsku::where('goods_id',$goodsData['goods_id'])->field('id,sku_name,sku_price,group_price,seckill_price,sku_img,stock,sku_weight')->select();
//            //处理商品SKU图片
//            if(!empty($goodsSku)){
//                foreach ($goodsSku as $key=>$value){
//                    $goodsSku[$key]['sku_img'] = get_img_path($value['sku_img']);
//                }
//            }
//            $goodsData['sku'] = $goodsSku;
//            //优惠券
//            $coupon = Db::name('qt_coupon')
//                ->field('id as coupon_id,satisfy,reduce,goods_id,img,start_time,end_time')
//                ->whereIn('goods_id',[$goodsData['goods_id'],'0'])
//                ->where('status',1)
//                ->select();
//            if(!empty($coupon)){
//                foreach ($coupon as $key=>$value){
//                    $coupon[$key]['img'] = get_img_path($value['img']);
//                    $is_get = 0;
//                    if(!empty($userInfo)){
//                        $get = Db::name('qt_coupon_list')->where(['cou_id'=>$value['coupon_id'],'user_id'=>$userInfo['id']])->count();
//                        $is_get = $get == 0 ? 0 : 1;
//                    }
//                    $coupon[$key]['is_get'] = $is_get;
//                }
//            }
//            $goodsData['coupon'] = $coupon;
//            //是否收藏
//            if(empty($userInfo)){
//                $is_like = 0;
//            }else{
//                $like = Db::name('qt_like')->where(['user_id'=>$userInfo['id'],'goods_id'=>$goodsId])->find();
//                if(empty($like)){
//                    $is_like = 0;
//                }else{
//                    $is_like = 1;
//                }
//            }
//            $goodsData['is_like'] = $is_like;
//
//
//            $this->result('查询成功',$goodsData,200);
//        }
//    }


    public function getSku()
    {
        if ($this->request->isGet()) {
            $goodsId = $this->request->get('goods_id');
        }
        if (empty($goodsId) || !isset($goodsId)) {
            $this->result('缺少参数', '', 204);
        }
        $goodsData = GoodsModel::where(['goods_id' => $goodsId, 'status' => 1])
            ->field('goods_id,goods_name,goods_price,goods_img')
            ->find();
        $goodsData['goods_img'] = get_img_path($goodsData['goods_img']);
        $goodsSku = Goodsku::where('goods_id', $goodsId)->field('id as sku_id,sku_name,sku_price,group_price,seckill_price,sku_img,stock,sku_weight')->select();
        //处理商品SKU图片
        if (!empty($goodsSku)) {
            foreach ($goodsSku as $key => $value) {
                $goodsSku[$key]['sku_img'] = get_img_path($value['sku_img']);
            }
        }
        $goodsData['sku'] = $goodsSku;
        $this->result('查询成功', $goodsData, 200);
    }

    /**
     * 商品项目关联添加
     * [{"product_id":"18","number":"1"},{"product_id":"20","number":"1"}]
     * [{"product_id":"10","number":"1","product_name":"果粒橙"}]
     *
     */
    public function goodsProductAdd(){
        if($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\Goods();
            if (!$validate->scene('goods_product')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $goods = Db::name('qt_goods_product')->where(['goods_id'=>$getData['goods_id']])->find();
            if(!empty($goods)){
                $this->result('当前项目商品已经添加过了','',204);
            }
            $getData['user_id']=$this->userInfo['id'];
            $getData['create_time']=time();
            $inset = Db::name('qt_goods_product')->insert($getData);
            if($inset){
                $this->result('添加成功','',200);
            }else{
                $this->result('添加失败','',204);
            }
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 商品项目关联删除
     */
    public function goodsProductDel(){
        if($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少关联信息','',204);
            }
            $goodsID = Db::name('qt_goods_product')->where(['id'=>$getData['id']])->value('goods_id');
            $del = Db::name('qt_goods_product')->where(['goods_id'=>$goodsID])->delete();
            if($del){
                $this->result('删除成功','',200);
            }else{
                $this->result('删除失败','',204);
            }
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 商品项目关联编辑
     */
    public function goodsProductEdit(){
        if($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\Goods();
            if (!$validate->scene('goods_product')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $update = Db::name('qt_goods_product')->where(['id'=>$getData['id']])->update($getData);
            if($update !==  false ){
                $this->result('修改成功','',200);
            }else{
                $this->result('修改失败','',204);
            }
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 商品项目关联列表
     */
    public function goodsProductList(){
        if($this->request->isPost()) {
            $data = Db::name('qt_goods_product')
                ->alias('gp')
                ->field('gp.id,g.name as goods_name,gp.goods_id,gp.product_data')
                ->leftJoin('qt_goods g','g.id = gp.goods_id')
                ->select();
            foreach ($data as $key=>$value){
                $product = json_decode($value['product_data'],true);
                $string = '';
                foreach ($product as $k=>$v){
                    $string.= $v['name']."X(".$v['number'].")".$v['unit'];
                }
                $data[$key]['product'] = $string;
            }
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }

}
